const app = getApp();
const AJAX = app.$ajax,
  $wx = app.$wx;

Page({
  data: {
    popupPaperboard: false,
    activePaperboardItem: -1,
    detail: {},
    isAbbr: false,
    paperboardLeftVal: 0,
    paperboardTopVal: 0
  },

  onLoad(options){
    let detail_config = JSON.parse(options.detail_config);
    
    detail_config.size[0] = parseInt(detail_config.size[0]);
    detail_config.size[1] = parseInt(detail_config.size[1]);
    
    this.setData({
      detailConfig: detail_config
    }, callback => {
      this.getPaperboardList();
    });
  },

  onShow(){
    let td = this.data;
    this.appData = app.appData || {};
    let selected_txture_item = this.appData.selected_txture_item || {};

    this.setData({
      selectedTxtureItem: selected_txture_item,
      borderWidth: selected_txture_item.iframewidth ?
       parseInt(selected_txture_item.iframewidth) * 2 : 0
    }, callback => {
      this.drawImgs(td.detailConfig.imgUrl, selected_txture_item.iframeimage);
    });
  },
  
  onUnload(){
    app.appData.selected_txture_item = {};
  },
  
  onShareAppMessage(){

  },

  drawImgs(imgUrl, borderImgUrl){
    let ctx = wx.createCanvasContext('canvas-detailImg', this);
    this.getSystemInfo(res => {
      let win_width = res.windowWidth, 
          win_height = res.windowHeight;

      console.log(win_width);
      ctx.drawImage(imgUrl, 0, 0);
      borderImgUrl && 
        ctx.drawImage(borderImgUrl, 0, 0, win_width, win_height)
      ctx.draw();
    });
    
  },

  getSystemInfo(callback) {
    callback && wx.getSystemInfo({
      success: res => {
        if (typeof callback === 'function') {
          callback(res);
        } else {
          throw new Error(callback + ' is not Function');
        }
      },
      fail() {
        $wx.showToast('获取设备信息失败');
      }
    })
  },
  
  selectedPaperboard(){
    this.setData({
      popupPaperboard: true
    });
  },

  popupCancel(){
    this.setData({
      popupPaperboard: false
    });
  },

  popupConfirm(){
    this.setData({
      popupPaperboard: false
    });
  },

  preview(){
    this.createDraw();
  },
  
  checkAbbr(e){
    let td = this.data, ed = e.currentTarget.dataset;
    this.setData({
      isAbbr: ed.index == 0 ? true : false
    });
  },

  addCart(){
    let app_data = this.appData;
    if (!app_data.selected_txture_item || Object.keys(app_data.selected_txture_item).length == 0){
      $wx.showToast('请选择边框');
    }
  },

  paperboardLeft(e){
    let ed = e.detail;
    this.setData({
      paperboardLeftVal: ed.value
    });
  },

  paperboardTop(e) {
    let ed = e.detail;
    this.setData({
      paperboardTopVal: ed.value
    });
  },

  getPaperboardItem(e){
    let ed = e.currentTarget.dataset;
    this.setData({
      activePaperboardItem: ed.index
    });
  },

  buy(){
    this.createOrder();
  },

  /**
   * 获取商品详情
   * @param id
   * */
  getGoodDetail() {
    let td = this.data;

    AJAX.goodDetail({
      loadType: 'bar',
      goods_id: td.detailId
    }).then(([status, res, msg]) => {
      if (status) {
        this.setData({
          detail: res.detail
        });
      } else {
        $wx.shosToast(msg);
      }
    });
  },

  /**
   * 收藏商品
   * @param goods_id
   * */
  collectGood(id) {
    let _this = this, td = _this.data;
    AJAX.collectGood({
      loadType: 'bar',
      goods_id: id
    }).then(([status, res, msg]) => {
      $wx.showToast(msg, {
        success() {
          td.detail.is_conllect = res.is_conllect;
          _this.setData({
            detail: td.detail
          });
        }
      });
    });
  },

  /**
   * 加入购物车
   * @param goods_id
   * @param goods_num
   * @param goods_sku_id
   * */
  addCart(e) {
    let td = this.data,
      detail_config = td.detailConfig,
      goods_sku_id = [];

    if(app.appData.selected_txture_item){
      detail_config && detail_config.specAttr.map(item => {
        goods_sku_id.push(item.spec_items[item.activeItem].item_id);
      });

      AJAX.addCart({
        loadType: 'default',
        loadMsg: '加入购车中...',
        goods_id: detail_config.detailId,
        goods_sku_id: JSON.stringify(goods_sku_id || []),
        goods_num: 1,
        goods_type: 20,
        is_boli: td.isAbbr ? 1 : 2,
        huakuang_id: app.appData.selected_txture_item.id,
        is_kazhi: td.activePaperboardItem > 0 ? td.paperboard[td.activePaperboardItem].id : 0,
        ...app.appData.selected_txture_itemParams,
        left: td.paperboardLeftVal,
        top: td.paperboardTopVal,
        chicun: td.detailConfig.size[0] + '*' + td.detailConfig.size[1],
      }).then(([status, res, msg]) => {
        $wx.showToast(msg);
      });
    }else{
      $wx.showToast('请选中规格');
    }
  },

  /**
   * 创建订单
   * */ 
  createOrder() {
    let td = this.data, 
        detail_config = td.detailConfig, 
        goods_sku_id = [];
    
    if (app.appData.selected_txture_item){
      detail_config && detail_config.specAttr.map(item => {
        goods_sku_id.push(item.spec_items[item.activeItem].item_id);
      });

      AJAX.createOrder({
        loadType: 'default',
        loadMsg: '加载中...',
        type: 2,
        goods_id: detail_config.detailId,
        goods_sku_id: JSON.stringify(goods_sku_id || []),
        goods_num: 1,
        goods_type: 20,
        is_boli: td.isAbbr ? 1 : 2,
        huakuang_id: app.appData.selected_txture_item.id,
        is_kazhi: td.activePaperboardItem > 0 ? td.paperboard[td.activePaperboardItem].id : 0,
        ...app.appData.selected_txture_itemParams,
        left: td.paperboardLeftVal,
        top: td.paperboardTopVal,
        chicun: td.detailConfig.size[0] + '*' + td.detailConfig.size[1],
      }).then(([status, res, msg]) => {
        if (status) {
          wx.setStorageSync("orderDetail", res);
          wx.navigateTo({
            url: '/pages/subpage/order/detail/detail'
          })
        } else {
          $wx.showToast(msg);
        }
      });
    }else{
      $wx.showToast('请选中规格');
    }
  },
  
  /**
   * 获取卡纸列表
   * */ 
  getPaperboardList(params = {}){
    AJAX.getPaperboardList(params).then(([status, res, msg]) => {
      if(status){
        this.setData({
          paperboard: res
        });
      }else{
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 创建画框图
   * */ 
  createDraw(){
    let td = this.data, preview_info = {};
    if(app.appData.selected_txture_item){
      AJAX.createDraw({
        loadType: 'default',
        loadMsg: '预览加载中...',
        goods_id: td.detailConfig.detailId,
        huakuang_id: app.appData.selected_txture_item.id,
        kazhi: td.activePaperboardItem > 0 ? td.paperboard[td.activePaperboardItem].id : '',
        juli: td.paperboardTopVal + ' ' + td.paperboardLeftVal
      }).then(([status, res, msg]) => {
        if(status){
          preview_info.imgUrl = res.img;
          wx.navigateTo({
            url: '/pages/subpage/custom-made/preview/preview?preview_info=' + JSON.stringify(preview_info)
          })
        }else{
          $wx.showToast(msg);
        }
      });
    } else {
      $wx.showToast('请选中规格');
    }
   
  }
});